package com.acme.tcp;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import com.acme.domain.bank.Bank;

public class BankServer implements Serializable {

	private static final long serialVersionUID = 1L;

	public void startServer(Bank bank) throws IOException,
			ClassNotFoundException {
		ServerSocket server = new ServerSocket(2345);
		System.out.println("Server created. Waiting for a client...");
		Socket connection = server.accept();
		System.out.println("Connection received from "
				+ connection.getInetAddress().getHostName());

		ObjectOutputStream out = new ObjectOutputStream(
				connection.getOutputStream());
		ObjectInputStream in = new ObjectInputStream(
				connection.getInputStream());

		String[] messageFromClient;
		String feed;

		System.out.println("Server ready for transaktion.");
		do {
			messageFromClient = (String[]) in.readObject();

			if (messageFromClient[0].equals("add")) {
				// information about new client:
				feed = messageFromClient[1];
				System.out.println("Message from client: " + feed);
				// adding new client in bank:
				BankReport bankReport = new BankReport();
				bank = bankReport.addClientFromFeed(bank, feed);

				out.writeObject("Sending...");
				System.out.println("Sending...");
				for (;;) {
					out.writeObject(bank);
					if (in.readObject().equals("bank is ok")) {
						break;
					}
				}
				System.out.println("Done.");
				out.writeObject("end");
			}
		} while (!(in.readObject().equals("end")));

		in.close();
		out.close();
		server.close();

	}
}
